import { DefenseSystem, TargetPriority } from '../entities/DefenseSystem.js';
import { Missile } from '../entities/Missile.js';
import { EntitySystem } from './EntitySystem.js';
import { GameConfig, DefenseSystemType } from '../config/GameConfig.js';

export class DefenseSystemManager {
    private entitySystem: EntitySystem;
    private defenseSystems: DefenseSystem[] = [];
    private targetingTimer: number = 0;
    private targetingInterval: number = 500; // 每500ms进行一次目标分配
    
    // 事件回调
    public onSystemBuilt: ((system: DefenseSystem) => void) | null = null;
    public onSystemDestroyed: ((system: DefenseSystem) => void) | null = null;
    public onInterceptAttempt: ((system: DefenseSystem, missile: Missile, success: boolean) => void) | null = null;

    constructor(entitySystem: EntitySystem) {
        this.entitySystem = entitySystem;
    }

    async init(): Promise<void> {
        console.log('🛡️ 初始化防御系统管理器...');
        console.log('✅ 防御系统管理器初始化完成');
    }

    update(deltaTime: number): void {
        this.targetingTimer += deltaTime;
        
        // 更新防御系统列表
        this.updateDefenseSystemsList();
        
        // 🔧 强制日志确认防御系统状态
        if (this.defenseSystems.length > 0) {
            const now = Date.now();
            if (!this.lastStatusLog || now - this.lastStatusLog > 3000) {
                console.log(`🛡️ 防御系统管理器状态:`);
                console.log(`   活跃防御系统: ${this.defenseSystems.length}`);
                this.defenseSystems.forEach((system, index) => {
                    console.log(`   系统${index + 1}: ${system.getSystemType()} @ (${system.x.toFixed(0)}, ${system.y.toFixed(0)}) - 状态: ${system.isReady() ? '准备就绪' : '忙碌'}`);
                });
                this.lastStatusLog = now;
            }
        }
        
        // 定期进行目标分配
        if (this.targetingTimer >= this.targetingInterval) {
            this.assignTargets();
            this.targetingTimer = 0;
        }
    }
    
    private lastStatusLog: number = 0;

    private updateDefenseSystemsList(): void {
        this.defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem).filter(system => system.active);
    }

    private assignTargets(): void {
        const missiles = this.entitySystem.getEntitiesOfType(Missile).filter(missile => missile.active);
        
        if (missiles.length === 0) return;
        
        // 为每个准备好的防御系统分配目标
        const readySystems = this.defenseSystems.filter(system => system.isReady());
        
        readySystems.forEach(system => {
            const target = this.selectBestTarget(system, missiles);
            if (target) {
                system.setTarget(target);
            }
        });
    }

    private selectBestTarget(system: DefenseSystem, missiles: Missile[]): Missile | null {
        // 过滤出射程内的导弹
        const missilesInRange = missiles.filter(missile => {
            const distance = Math.sqrt(
                Math.pow(missile.x - system.x, 2) + 
                Math.pow(missile.y - system.y, 2)
            );
            return distance <= system.getRange();
        });

        if (missilesInRange.length === 0) return null;

        // 根据优先级排序
        const priority = system.getTargetPriority();
        const sortedMissiles = this.sortMissilesByPriority(missilesInRange, system, priority);
        
        return sortedMissiles[0] || null;
    }

    private sortMissilesByPriority(missiles: Missile[], system: DefenseSystem, priority: TargetPriority): Missile[] {
        return missiles.sort((a, b) => {
            switch (priority) {
                case TargetPriority.DISTANCE:
                    return this.getDistance(a, system) - this.getDistance(b, system);
                
                case TargetPriority.THREAT_LEVEL:
                    return this.getThreatLevel(b) - this.getThreatLevel(a); // 高威胁优先
                
                case TargetPriority.SPEED:
                    const speedA = Math.sqrt(a.getVelocity().x ** 2 + a.getVelocity().y ** 2);
                    const speedB = Math.sqrt(b.getVelocity().x ** 2 + b.getVelocity().y ** 2);
                    return speedB - speedA; // 高速优先
                
                case TargetPriority.HEALTH:
                    return a.getHealth() - b.getHealth(); // 低血量优先
                
                default:
                    return this.getThreatLevel(b) - this.getThreatLevel(a);
            }
        });
    }

    private getDistance(missile: Missile, system: DefenseSystem): number {
        return Math.sqrt(
            Math.pow(missile.x - system.x, 2) + 
            Math.pow(missile.y - system.y, 2)
        );
    }

    private getThreatLevel(missile: Missile): number {
        const type = missile.getMissileType();
        const damage = missile.getDamage();
        const speed = Math.sqrt(missile.getVelocity().x ** 2 + missile.getVelocity().y ** 2);
        
        // 威胁等级计算：伤害 * 速度系数 * 类型系数
        let typeMultiplier = 1;
        
        switch (type) {
            case 'FATTAH_2':
                typeMultiplier = 3; // 超音速导弹最高威胁
                break;
            case 'SHAHAB_3':
            case 'ZELZAL_2':
                typeMultiplier = 2; // 中程导弹高威胁
                break;
            case 'FATEH_110':
            case 'QIAM_1':
                typeMultiplier = 1.5; // 短程导弹中等威胁
                break;
            case 'SHAHED_136':
                typeMultiplier = 0.8; // 无人机威胁较低
                break;
        }
        
        return damage * (1 + speed / 100) * typeMultiplier;
    }

    // 建造防御系统
    public buildDefenseSystem(type: DefenseSystemType, gridX: number, gridY: number): DefenseSystem | null {
        // 检查网格是否被占用
        if (this.entitySystem.isGridOccupied(gridX, gridY)) {
            console.warn(`⚠️ 网格 (${gridX}, ${gridY}) 已被占用`);
            return null;
        }

        // 检查特殊限制
        if (!this.checkBuildingRestrictions(type, gridX, gridY)) {
            return null;
        }

        const systemId = this.entitySystem.generateEntityId();
        const system = new DefenseSystem(systemId, type, gridX, gridY);
        
        this.entitySystem.addEntity(system);
        this.entitySystem.occupyGrid(gridX, gridY, systemId);
        this.defenseSystems.push(system);
        
        console.log(`🏗️ 建造 ${type} 于网格 (${gridX}, ${gridY})`);
        
        if (this.onSystemBuilt) {
            this.onSystemBuilt(system);
        }
        
        return system;
    }

    private checkBuildingRestrictions(type: DefenseSystemType, gridX: number, gridY: number): boolean {
        // 箭-3系统只能建造在后排
        if (type === 'ARROW_3' && gridX < 3) {
            console.warn('⚠️ 箭-3系统只能部署在后排');
            return false;
        }
        
        // 检查是否有足够的空间（某些系统可能需要2x2的空间）
        // 目前所有系统都是1x1，未来可以扩展
        
        return true;
    }

    // 销毁防御系统
    public destroyDefenseSystem(systemId: string): void {
        const system = this.defenseSystems.find(s => s.id === systemId);
        if (!system) return;

        // 释放网格
        const defenseAreaStartX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        const gridX = Math.floor((system.x - defenseAreaStartX) / GameConfig.DEFENSE_GRID_SIZE);
        const gridY = Math.floor(system.y / GameConfig.DEFENSE_GRID_SIZE);
        
        this.entitySystem.freeGrid(gridX, gridY);
        
        // 移除实体
        system.destroy();
        this.entitySystem.removeEntity(systemId);
        
        // 从列表中移除
        const index = this.defenseSystems.findIndex(s => s.id === systemId);
        if (index !== -1) {
            this.defenseSystems.splice(index, 1);
        }
        
        console.log(`💥 销毁防御系统 ${systemId}`);
        
        if (this.onSystemDestroyed) {
            this.onSystemDestroyed(system);
        }
    }

    // 设置全局目标优先级
    public setGlobalTargetPriority(priority: TargetPriority): void {
        this.defenseSystems.forEach(system => {
            system.setTargetPriority(priority);
        });
        console.log(`🎯 全局目标优先级设置为: ${priority}`);
    }

    // 获取防御系统统计
    public getDefenseStats(): {
        total: number;
        byType: Record<DefenseSystemType, number>;
        totalCost: number;
        maintenanceCost: number;
    } {
        const stats = {
            total: this.defenseSystems.length,
            byType: {
                IRON_DOME: 0,
                ARROW_3: 0,
                GREEN_PINE_RADAR: 0
            } as Record<DefenseSystemType, number>,
            totalCost: 0,
            maintenanceCost: 0
        };

        this.defenseSystems.forEach(system => {
            const type = system.getSystemType();
            stats.byType[type]++;
            stats.totalCost += system.getCost();
            stats.maintenanceCost += system.getMaintenanceCost();
        });

        return stats;
    }

    // 获取射程覆盖率
    public getCoverageAnalysis(): {
        totalCoverage: number;
        gridCoverage: boolean[][];
        vulnerableAreas: { x: number; y: number }[];
    } {
        const gridCoverage: boolean[][] = [];
        const vulnerableAreas: { x: number; y: number }[] = [];
        
        // 初始化网格覆盖
        for (let row = 0; row < GameConfig.DEFENSE_GRID_ROWS; row++) {
            gridCoverage[row] = [];
            for (let col = 0; col < GameConfig.DEFENSE_GRID_COLS; col++) {
                gridCoverage[row][col] = false;
            }
        }
        
        // 计算每个防御系统的覆盖范围
        this.defenseSystems.forEach(system => {
            const range = system.getRange();
            
            for (let row = 0; row < GameConfig.DEFENSE_GRID_ROWS; row++) {
                for (let col = 0; col < GameConfig.DEFENSE_GRID_COLS; col++) {
                    const defenseAreaStartX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
                    const gridCenterX = defenseAreaStartX + col * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2;
                    const gridCenterY = row * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2;
                    
                    const distance = Math.sqrt(
                        Math.pow(gridCenterX - system.x, 2) + 
                        Math.pow(gridCenterY - system.y, 2)
                    );
                    
                    if (distance <= range) {
                        gridCoverage[row][col] = true;
                    }
                }
            }
        });
        
        // 统计覆盖率和找出脆弱区域
        let coveredCells = 0;
        const totalCells = GameConfig.DEFENSE_GRID_ROWS * GameConfig.DEFENSE_GRID_COLS;
        
        for (let row = 0; row < GameConfig.DEFENSE_GRID_ROWS; row++) {
            for (let col = 0; col < GameConfig.DEFENSE_GRID_COLS; col++) {
                if (gridCoverage[row][col]) {
                    coveredCells++;
                } else {
                    const defenseAreaStartX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
                    vulnerableAreas.push({
                        x: defenseAreaStartX + col * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2,
                        y: row * GameConfig.DEFENSE_GRID_SIZE + GameConfig.DEFENSE_GRID_SIZE / 2
                    });
                }
            }
        }
        
        return {
            totalCoverage: (coveredCells / totalCells) * 100,
            gridCoverage,
            vulnerableAreas
        };
    }

    // 获取所有防御系统
    public getDefenseSystems(): DefenseSystem[] {
        return [...this.defenseSystems];
    }

    // 根据类型获取防御系统
    public getDefenseSystemsByType(type: DefenseSystemType): DefenseSystem[] {
        return this.defenseSystems.filter(system => system.getSystemType() === type);
    }

    // 获取最近的防御系统
    public getNearestDefenseSystem(x: number, y: number): DefenseSystem | null {
        if (this.defenseSystems.length === 0) return null;

        return this.defenseSystems.reduce((nearest, current) => {
            const currentDistance = Math.sqrt(Math.pow(current.x - x, 2) + Math.pow(current.y - y, 2));
            const nearestDistance = Math.sqrt(Math.pow(nearest.x - x, 2) + Math.pow(nearest.y - y, 2));
            
            return currentDistance < nearestDistance ? current : nearest;
        });
    }
}
